#!/usr/bin/env python3
"""
邮件同步服务 - 启动脚本
功能：启动独立的邮件同步服务
支持平台：Windows、Linux、macOS
"""

import subprocess
import sys
import os
from pathlib import Path

def get_python_executable():
    """获取当前Python解释器路径"""
    return sys.executable

def main():
    """启动同步服务"""
    print("=" * 60)
    print("邮件同步服务")
    print("=" * 60)
    print(f"Python版本: {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}")
    print(f"Python路径: {get_python_executable()}")
    print("=" * 60)
    
    # 设置工作目录为项目根目录
    project_dir = Path(__file__).parent.parent
    os.chdir(project_dir)
    
    # 设置PYTHONPATH
    env = os.environ.copy()
    pythonpath = str(project_dir)
    if 'PYTHONPATH' in env:
        pythonpath = pythonpath + os.pathsep + env['PYTHONPATH']
    env['PYTHONPATH'] = pythonpath
    
    # 启动同步服务（直接运行Python脚本，不是通过uvicorn）
    python_exe = get_python_executable()
    sync_script = project_dir / "api" / "sync_service.py"
    cmd = [python_exe, str(sync_script)]
    
    print(f"\n正在启动同步服务...")
    print(f"命令: {' '.join(cmd)}\n")
    
    try:
        subprocess.run(cmd, check=True, env=env)
    except subprocess.CalledProcessError as e:
        print(f"\n错误: 同步服务启动失败 - {e}")
        sys.exit(1)
    except KeyboardInterrupt:
        print("\n\n同步服务已停止")
        sys.exit(0)
    except Exception as e:
        print(f"\n发生未预期的错误: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()